<template>
  <div class="register-container">
    <el-form ref="registerForm" :model="registerData" :rules="registerRules" class="register-form">
      <div class="title-container">
        <h3 class="title">视频解析系统注册</h3>
      </div>

      <el-form-item prop="username">
        <el-input
          v-model="registerData.username"
          placeholder="用户名"
          type="text"
          tabindex="1"
          :prefix-icon="User"
        />
      </el-form-item>

      <el-form-item prop="password">
        <el-input
          v-model="registerData.password"
          placeholder="密码"
          :type="passwordType"
          tabindex="2"
          :prefix-icon="Lock"
          @keyup.enter="handleRegister"
        >
          <template #suffix>
            <el-icon class="show-pwd" @click="showPwd">
              <component :is="passwordType === 'password' ? 'Hide' : 'View'" />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="confirmPassword">
        <el-input
          v-model="registerData.confirmPassword"
          placeholder="确认密码"
          :type="confirmPasswordType"
          tabindex="3"
          :prefix-icon="Lock"
          @keyup.enter="handleRegister"
        >
          <template #suffix>
            <el-icon class="show-pwd" @click="showConfirmPwd">
              <component :is="confirmPasswordType === 'password' ? 'Hide' : 'View'" />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item prop="nickname">
        <el-input
          v-model="registerData.nickname"
          placeholder="昵称"
          type="text"
          tabindex="4"
          :prefix-icon="UserFilled"
        />
      </el-form-item>

      <el-form-item prop="phone">
        <el-input
          v-model="registerData.phone"
          placeholder="手机号码"
          type="text"
          tabindex="5"
          :prefix-icon="Iphone"
        />
      </el-form-item>

      <el-form-item prop="email">
        <el-input
          v-model="registerData.email"
          placeholder="邮箱"
          type="text"
          tabindex="6"
          :prefix-icon="Message"
        />
      </el-form-item>

      <el-form-item prop="captcha">
        <el-input
          v-model="registerData.captcha"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          tabindex="7"
          :prefix-icon="CircleCheck"
        />
        <div class="register-code">
          <img :src="captchaUrl" @click="getCode" class="register-code-img" />
        </div>
      </el-form-item>

      <el-button :loading="loading" type="primary" style="width: 100%; margin-bottom: 30px" @click="handleRegister">注册</el-button>

      <div class="tips">
        <span>已有账号? </span>
        <router-link to="/login" class="link-type">立即登录</router-link>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, UserFilled, Iphone, Message, CircleCheck } from '@element-plus/icons-vue'
import { register, getCodeImg } from '@/api/auth'

const router = useRouter()

// 注册表单引用
const registerForm = ref(null)

// 注册表单数据
const registerData = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  phone: '',
  email: '',
  captcha: '',
  captchaKey: '',
  uuid: ''
})

// 注册校验规则
const registerRules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度必须在2到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6到20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerData.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  nickname: [
    { required: true, message: '昵称不能为空', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '手机号码不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '验证码不能为空', trigger: 'blur' }
  ]
}

// 加载状态
const loading = ref(false)

// 验证码图片
const captchaUrl = ref('')
const captchaKey = ref('')

// 密码类型
const passwordType = ref('password')
const confirmPasswordType = ref('password')

// 显示密码
const showPwd = () => {
  passwordType.value = passwordType.value === 'password' ? '' : 'password'
}

// 显示确认密码
const showConfirmPwd = () => {
  confirmPasswordType.value = confirmPasswordType.value === 'password' ? '' : 'password'
}

// 获取验证码
const getCode = () => {
  // getCodeImg().then(res => {
  //   codeUrl.value = 'data:image/gif;base64,' + res.img
  //   registerData.uuid = res.uuid
  // })
  // 生成随机验证码key
  captchaKey.value = new Date().getTime().toString()
  registerData.captchaKey = captchaKey.value
  // 设置验证码URL
  captchaUrl.value = `http://localhost:8080/api/auth/captcha?key=${captchaKey.value}&t=${new Date().getTime()}`
}

// 处理注册
const handleRegister = () => {
  registerForm.value.validate(valid => {
    if (valid) {
      loading.value = true
      register(registerData).then(() => {
        loading.value = false
        ElMessage.success('注册成功，请登录')
        router.push('/login')
      }).catch(() => {
        loading.value = false
        getCode()
      })
    }
  })
}

// 初始化获取验证码
getCode()
</script>

<style lang="scss" scoped>
$bg: #283443;
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .register-container .el-input input {
    color: $cursor;
  }
}

.register-container {
  height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  
  .register-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }
  
  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;
    
    .link-type {
      color: #409EFF;
    }
  }
  
  .title-container {
    position: relative;
    
    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0 auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }
  
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $cursor;
    cursor: pointer;
    user-select: none;
  }
  
  .register-code {
    width: 33%;
    height: 40px;
    float: right;
    
    img {
      cursor: pointer;
      vertical-align: middle;
      width: 100%;
      height: 40px;
    }
  }
}
</style>